package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

import org.datanucleus.store.mapped.expression.ScalarExpression.IllegalOperationException;

public class Utils {
	public static String returnSubDomain(String domain) {
		String re_domain = domain;
		re_domain = re_domain.replaceAll("com[.]{1}[a-zA-Z]+$", "");
		ResourceBundle resource = ResourceBundle.getBundle("language",
				new Locale("en"));
		String[] check = resource.getString("domain").split(" ");
		for (int i = 0; i < check.length; i++) {
			re_domain = re_domain.replaceAll("[.]+"+check[i]+"$", "");
		}
		
		re_domain = re_domain.replaceAll("[.]+$", "");
		
		String str = re_domain.replaceAll("[.]{1}[^.]+$", "");
		
		if (re_domain.length() != str.length()) {
			
			return " is sub domain of <strong>"
					+ domain.replaceAll(str+"[.]{1}", "")
					+ "</strong>";
		} else {
				return " is top level domain";
		}
	}
	public static String cleanContent(String str)
	{
		str = str.replaceAll("(class|id)[ ]*[=]{1}[ ]*[\\\'\\\"]{1}[^\\\'\\\"]+[\\\'\\\"]{1}", "");
		str = str.replaceAll("<script[^<]+</script[ ]*>", "");
		return str;
	}
	public static String fomatDomain(String str) {
		if (str != null)
			str = str.toLowerCase().replaceAll("(http|https)+://", "")
					.replaceAll("^[\\w\\W]+[\\/]{2}", "")
					.replaceAll("[\\/]+[\\w\\W]*$", "")
					.replaceAll("[\\?]+[\\w\\W]*$", "")
					.replaceAll("[ !@#$%^&*?()\\[\\]{}+=,:;|\\\'\\\"/\\\\`~]+", "").replaceAll("^[.]{1}", "")
					.trim();

		return str;
	}
	public static String returnDomain(String domain) {
		String re_domain = domain;
		re_domain = re_domain.replaceAll("com[.]{1}[a-zA-Z]+$", "");
		ResourceBundle resource = ResourceBundle.getBundle("language",
				new Locale("en"));
		String[] check = resource.getString("domain").split(" ");
		for (int i = 0; i < check.length; i++) {
			re_domain = re_domain.replaceAll("[.]+"+check[i]+"$", "");
		}
		
		re_domain = re_domain.replaceAll("[.]+$", "");

		String str = re_domain.replaceAll("[.]{1}[^.]+$", "");
		
		if (re_domain.length() != str.length()) {
			
			return re_domain.replaceAll(str+"[.]{1}", "");
		} else {
			return re_domain;
		}
	}
	public static Boolean checkDomain(String domain) {
		ResourceBundle resource = ResourceBundle.getBundle("language",
				new Locale("en"));
		String re_domain = domain;

		String[] listDomain = resource.getString("domain").split(" ");
		for (int i = 0; i < listDomain.length; i++) {
			re_domain = re_domain
					.replaceAll("[.]{1}" + listDomain[i] + "$", "");
		}

		if (re_domain.length() != domain.length()) {
			return true;
		}

		return false;
	}
	public static String returnWhois(String str,String domain)
		throws NoSuchAlgorithmException {
		Pattern p = Pattern.compile("[^ :]+@[^ ]+");
		
		Matcher m = p.matcher(str.replaceAll("\\<.*?\\>", " "));
		String email = "";
		while (m.find()) {
			email = m.group().trim().replaceAll("\\(", "")
					.replaceAll("\\)", "");
			
			str = str
					.replaceAll(
							email.replaceAll("\\*", ""),
							"<img alt='whois "+domain+"' src='http://source.domaintools.com/email.pgif?md5="
									+ md5(email.toLowerCase().replaceAll("\\*", ""))
									+ "&face=arial&size=9&color=000000&bgcolor=FFFFFF&face=arial&size=9&color=0000FF&bgcolor=FFFFFF&format[]=underline&format[]=transparent&format[]=transparent'/>");
			
		}
		
		return str;
	}
	public static String md5(String str) throws NoSuchAlgorithmException {
		MessageDigest md;

		md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes());

		byte byteData[] = md.digest();

		// convert the byte to hex format method 1
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < byteData.length; i++) {
			sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
					.substring(1));
		}

		str = sb.toString();
		return str;
	}
	public static String GetHtml(String link,String charset){
		String content="";
		
		URL url;
		try {
			url = new URL(link);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		    connection.setInstanceFollowRedirects(true);
		    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.21) Gecko/20110830 AlexaToolbar/alxf-2.14 AlexaToolbar/pXVUnvuf-1.2 Firefox/3.6.21");
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
			connection.setRequestProperty("Accept-Charset", "	ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			connection.setRequestProperty("Connection", "keep-alive");
			connection.setRequestProperty("Keep-Alive", "115");
			connection.setRequestProperty("Cookie", "PREF=ID=987bb7a56b1cc7bc:U=691fa246d56f502e:FF=0:TM=1314876638:LM=1314876681:S=yBXzqp_WQq9ykX-j; NID=50=nfNXg7ymSSsfdzMnkEuo7t1GCgIEwcK5xmpFhu1mQWwvNI5nFHLZpRsy_1XnaoKrdj9hnz7za9-M2OIO99phfFSTmXln-xCvqzJaRWHsN0EQKgpmkvgUDTWPVF4I4c9L; SID=DQAAALcAAADhqr-J8Ls3CKhmbRjwTMMP1DjmIvR8qBFxv99saTaFFgoRsVf18W4p_BTocYoxYNMvsvh9sfjMj7KqLyd_s9Y0lwYY_Rrljd7t5IpKBTWWnsv9VSJ_qelH943zV8YIT3uuIdJbHhFlCnVEu_YealZoldWjf4VirYR0PIrr0i4_JU2JCHRmpyW0ACt3KcyLkukJlGDyT5yC5js3CBSTAhnWSylBpMWPWyWJzqXe2BQFcdfuU_qo00pAR-uEcMQ437M; HSID=A9Z-j3CKhzDEykAES");
			connection.setRequestProperty("Cache-Control", "max-age=0");
			BufferedReader reader=null;
			if("gzip".equals(connection.getContentEncoding()))
		    {
				reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), Charset.forName(charset)));
		    } else {
		    	reader= new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName(charset)));
		    }
			char[] buf = new char[102102];
			int numRead=0;
	        while((numRead=reader.read(buf)) != -1){
	            String readData = String.valueOf(buf, 0, numRead);
	            content += readData;
	            buf = new char[102102];
	        }
	        reader.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return content;
	}
	
	public static String cleanWhois(String str)
	{
		str = str.replaceAll("\\<a[^>]+[>]{1}", "").replaceAll("</a>", "").replaceAll("style=\\\"padding-bottom:25px;\\\"", "");
		return str;
	}
	public static String returnSubDomainTo(String domain) {
		String re_domain = domain;
		re_domain = re_domain.replaceAll("com[.]{1}[a-zA-Z]+$", "");
		ResourceBundle resource = ResourceBundle.getBundle("language",
				new Locale("en"));
		String[] check = resource.getString("domain").split(" ");
		for (int i = 0; i < check.length; i++) {
			re_domain = re_domain.replaceAll("[.]+"+check[i]+"$", "");
		}
		
		re_domain = re_domain.replaceAll("[.]+$", "");

		String str = re_domain.replaceAll("[.]{1}[^.]+$", "");
		
		if (re_domain.length() != str.length()) {
			
			return domain.replaceAll(str+"[.]{1}", "");
		} else {
			return domain;
		}
	}
}
